// pages/address/list/index.js
import { getAddressList, deleteAddress } from '../../../api/address'
import { swipeCell } from '@/behaviors/swipeCell'
const app = getApp()
Page({
  // 页面的初始数据
  behaviors: [swipeCell],
  data: {
    addressList: []
  },
  async getAddressData(){
    const { data } = await getAddressList() 
    this.setData({addressList: data})
  },
  changeAddress(e){
    if(this.flag !== '1') return
    const { id } = e.currentTarget.dataset
    const selectAddress = this.data.addressList.find(item => item.id === id)
    // const selectAddress = this.data.addressList.filter(item => item.id === id)
    if(selectAddress){
      app.globalData.address = selectAddress
      wx.navigateBack()
    }
  },
  onShow(){
    this.getAddressData()
  },
  onLoad(options){
    this.flag = options.flag
  },
  // 去编辑页面
  toEdit(e) {
    const { id } = e.currentTarget.dataset 
    wx.navigateTo({
      url: `/modules/settingModule/pages/address/add/index?id=${id}`
    })
  },
  async deleteAddress(e){
    const { id } = e.currentTarget.dataset
    const modalRes = await wx.modal({
      content: '你确定删除该收货地址吗？'
    })
    if(modalRes){
      await deleteAddress(id)
      wx.toast({title: '删除成功'})
      this.getAddressData()
    }
  },
})
